/*
    libnbds
    Non-blocking Data Structures Library

    Copyright (C) 2011 Paweł Dziepak

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "atomic.h"
#include "lifo.h"

using namespace nbds;

void lifo_base::push_(void *obj) {
	elem *x = new elem;
	x->obj = obj;

	elem *old_first = NULL;

	do {
		do {
			old_first = arch::get(&first);
			hp.set(old_first);
		} while (arch::get(&first) != old_first);

		x->next = old_first;
	} while (arch::cmp_and_swp(&first, old_first, x) != old_first);

	hp.release();
}

void *lifo_base::pop_() {
	elem *x = NULL;

	do {
		do {
			x = arch::get(&first);
			hp.set(x);
		} while (arch::get(&first) != x);

		if (!x)
			return NULL;
	} while (arch::cmp_and_swp(&first, x, arch::get(&x->next)) != x);

	void *obj = x->obj;
	hp.retire(x);

	return obj;
}

